/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.support.scripting.impl.js;

import cn.easyplatform.ScriptEvalExitException;
import cn.easyplatform.contexts.RecordContext;
import cn.easyplatform.interceptor.CommandContext;
import cn.easyplatform.support.scripting.ExpressionEngine;
import cn.easyplatform.support.scripting.RhinoScriptable;
import cn.easyplatform.support.scripting.ScriptUtils;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.RhinoException;
import org.mozilla.javascript.WrappedException;
import org.mozilla.javascript.Wrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * @author <a href="mailto:davidchen@epclouds.com">littleDog</a> <br/>
 * @since 2.0.0 <br/>
 */
public class RhinoExpressionEngine implements ExpressionEngine {

    private final static Logger log = LoggerFactory.getLogger(RhinoExpressionEngine.class);

    private RhinoScriptable scope = null;

    @Override
    public Object eval(CommandContext cc, String script, RecordContext... rcs) {
        RecordContext rc = rcs.length > 1 ? rcs[1] : rcs[0];
        script = ScriptUtils.parse(cc, rc, script);
        Context cx = Context.enter();
        try {
            cx.setOptimizationLevel(-1);
            scope = new RhinoScriptable();
            scope.initStandardObjects(cx, false);
            //ScriptCmdExecutor cmd =
            ScriptUtils.createVariables(scope, cc,
                    cc.getWorkflowContext(), rcs);
            cx.evaluateString(scope, RhinoScriptEngine.functions, "", 1, null);
            if (cc.getUser().isDebugEnabled())
                cc.send("script:" + script);
            else if (log.isDebugEnabled())
                log.debug("script {}", script);
//			if (cc.getUser().isDebugLogicEnabled()) {
//				cc.send(I18N.getLable("script.engine.system.var", cmd
//						.getTarget().getSystemVars()));
//				cc.send(I18N.getLable("script.engine.user.var","onExpr"));
//				cc.send(cmd.getTarget().getUserVars());
//				cc.send(I18N.getLable("script.engine.field.var","onExpr"));
//				cc.send(cmd.getTarget().getRecordFieldValues());
//				cc.send("script:" + script);
//			}
            Object result = cx.evaluateString(scope, script, "", 1, null);
//			if (cc.getUser().isDebugLogicEnabled()) {
//				cc.send(I18N.getLable("script.engine.system.var", cmd
//						.getTarget().getSystemVars()));
//				cc.send(I18N.getLable("script.engine.user.var","onExpr"));
//				cc.send(cmd.getTarget().getUserVars());
//				cc.send(I18N.getLable("script.engine.field.var","onExpr"));
//				cc.send(cmd.getTarget().getRecordFieldValues());
//			}
            if (result == null)
                return null;
            else if (result instanceof Wrapper)
                return ((Wrapper) result).unwrap();
            else
                return result;
        } catch (RhinoException ex) {
            if (ex instanceof WrappedException) {
                Throwable we = ((WrappedException) ex).getWrappedException();
                if (we instanceof ScriptEvalExitException) {
                    ScriptEvalExitException eval = (ScriptEvalExitException) we;
                    return eval.getMessage();
                }
            }
            throw ScriptUtils.handleScriptException(cc, ex);
        } finally {
            Context.exit();
            scope.clear();
            scope = null;
        }
    }
}
